/**
 * The TextEditor user-interface component class
 * @class syslib.ui.Box
 * @author Gabriel Ricci
 */
syslib.ui.TextEditor = __class(syslib.ui.VisualTag, 
/**
 * @lends syslib.ui.TextEditor
 */
{
	id : null, 
	lineBreak : true, 
	
	prepare : function(){
		// get the tag attributes
		var attributes = this.__attributes;
		
		// set this class attributes
		this.addProperty("string", "id", "");
		this.addProperty("boolean", "lineBreak", true);

		// load the style
		syslib.loadStyleForComponent('texteditor');
		
		// set some data
		this.id = (__valid(attributes.id)) ? attributes.id : syslib.element.generateID();
		this.lineBreak = __valid(attributes.linebreak && attributes.linebreak == "false") ? false : true;
		
		// return
		return true;
	},

	execute : function(){
		// attributes
		var styleText 	= this.__attributes.style;
		var attribs		= syslib.object.extend(this.__attributes, {
			"class" : "texteditor_textarea",
			"innerName" : "textarea",
			"id" : this.id,
			"style" : styleText
		});

		// JSON STRUCTURE
		var elemtJSON = ["table", {"border" : 0, "cellpadding" : 0, "cellspacing" : 0, "style" : styleText},
							["tbody",
								["tr",
									["td", {"innerName" : "textareatd", "class" : "texteditor_textarea_container"},
										["textarea", attribs,
											this.__innerHTML
										]
									]
								],
								["tr",
									["td", {"innerName" : "bottombartd", "class" : "texteditor_bottombar"},
										"&nbsp;"
									]
								]
							]
						];

		// CREATE THE OBJECT
		var editor = this.createDOM(elemtJSON);

		// RETURN
		return editor;
	},

	finalize : function(){
		var attribs	= this.__attributes;

		syslib.ui.TextEditor.countChars(this.__refs.textarea, this.__refs.bottombartd);
		
		syslib.event.listen('keydown', this.__refs.textarea, function(evt){
			// get the keycode
			var code = syslib.event.getKeyCode(evt);
			
			// verify if line break is allowed 
			if(code == 13 && !this.lineBreak){
				syslib.event.stopPropagation(evt);
			}
			
			// check the maxlength
			if(attribs.maxlength){
				if(syslib.event.isSpecialCode(evt)){
					return true;
				} else {
					if(syslib.ui.TextEditor.countChars(this.__refs.textarea, this.__refs.bottombartd) >= attribs.maxlength ){
						syslib.event.stopPropagation(evt);
					}
				}
			}
		}.applyTo(this));

		syslib.event.listen('keyup', this.__refs.textarea, function(evt){
			syslib.ui.TextEditor.countChars(this.__refs.textarea, this.__refs.bottombartd);
		}.applyTo(this));
	}
});

syslib.ui.TextEditor.countChars = function(textarea, updateElement){
	var count = textarea.value.length;
	syslib.element.update(updateElement, count);

	return count;
}